package weavingdraft;
import java.awt.GridLayout;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JPanel;

/**
 * @author Justin Wong
 * @version 1.0
 * 
 * This is a JPanel class that holds the squares to the pattern to display. 
 *
 */

public class PatternGrid extends JPanel implements Observer{
	/**
	 * Weaving draft the object refers to. 
	 */
	private WeavingDraft my_draft;
	/**
	 * The length of the sides. 
	 */
	private int long_side;
	/**
	 * The array of the pattern squares. 
	 */
	private PatternSquare[] squares;
	
	/**
	 * The constructor to create the object and display the weavingdraft pattern
	 * by the contestant. 
	 * @param the_draft the weavingdraft object referred to. 
	 */
	public PatternGrid(WeavingDraft the_draft){
		my_draft = the_draft;
		long_side = my_draft.getLongside();
		squares = new PatternSquare[long_side*long_side];
		
		my_draft.addObserver(this);
		this.setLayout(new GridLayout(long_side, long_side));
		createSquares();
	}
	/**
	 * This method creates the squares in the pattern grid. 
	 */
	private void createSquares(){
		int pos = 0;
		for(int i = 0; i < long_side; i++){
			for(int j = 0; j < long_side; j++){
				PatternSquare panel = new PatternSquare(i, j);
				this.add(panel);
				squares[pos] = panel;
				pos++;
			}
		}
	}
	/**
	 * This method will color the squares either black or white. 
	 */
	private void updateSquares(){
		for(PatternSquare s: squares){
			int row = s.getRow();
			int column = s.getColumn();
			int digit = my_draft.getPattern(row, column);
			if(digit == 1){
				s.setBlack();
			}else{
				s.setWhite();
			}
		}
	}
	@Override
	public void update(Observable o, Object arg) {
		updateSquares();
	}
}
